package com.lhb.common.utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.swing.*;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtils {


   static String fileName="C:\\Users\\86131\\Desktop\\student-management\\src\\main\\resources\\template\\学生信息模板.xlsx";

    public static void exportToExcel(JTable table) {
        try {



            // 创建一个工作簿
            Workbook workbook = new XSSFWorkbook();
            // 创建一个工作表
            Sheet sheet = workbook.createSheet("Sheet1");

            // 获取JTable的列名
            List<String> columnNames = new ArrayList<>();
            for (int i = 0; i < table.getColumnCount(); i++) {
                columnNames.add(table.getColumnName(i));
            }

            // 创建表头行
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < columnNames.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(columnNames.get(i));
            }

            // 填充数据行
            for (int i = 0; i < table.getRowCount(); i++) {
                Row dataRow = sheet.createRow(i + 1);
                for (int j = 0; j < table.getColumnCount(); j++) {
                    Cell cell = dataRow.createCell(j);
                    cell.setCellValue(table.getValueAt(i, j).toString());
                }
            }

            // 保存到文件
            FileOutputStream fileOut = new FileOutputStream(fileName);
            workbook.write(fileOut);
            fileOut.close();

         JOptionPane.showMessageDialog(null,"数据已成功导出到Excel文件: " + fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
